package com.chiang.apntest.plugin;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.chiang.apntest.common.Constant;
import com.chiang.apntest.service.SysMessageService;

import android.content.Intent;
import android.util.Log;

public class ApnPlugin extends CordovaPlugin{

	private static final String TAG="ApnPlugin";
	
	@Override
	public boolean execute(String action, final JSONArray jsonArray, final CallbackContext callbackContext) throws JSONException {
		if("connXmppServer".equals(action)){
			//Cannot refer to a non-final variable password inside 
			//an inner class defined in a different method
			//String username=jsonArray.getString(0);
			JSONObject jsonObject=(JSONObject) jsonArray.get(0);
			String username=jsonObject.getString("username");
			String password=jsonObject.getString("password");
			/********************A right way*****************************/
//			connXmppServer(jsonArray, callbackContext);
			
			/******************Better******************************
			 * The plugin's JavaScript does not run in the main thread of the WebView interface; 
			 * instead, it runs on the WebCore thread, as does the execute method. 
			 * If you need to interact with the user interface, you should use the following variation:
			 */
			/*cordova.getActivity().runOnUiThread(new Runnable(){
				@Override
				public void run() {
					connXmppServer(username, password,callbackContext);
				}
				
			});*/
			connXmppServer(username, password,callbackContext);
			return true;
		}
		return false;
	}

	private void connXmppServer(String username, String password, CallbackContext callbackContext) {
		Log.i(TAG, "-------ApnPlugin->connXmppServer--usernmae:"+username);
		Intent intent=new Intent();
		intent.putExtra(Constant.ACTION, Constant.ACTION_CONNECT_XMPP);
		intent.putExtra(Constant.KEY_USERNAME, username);
		intent.putExtra(Constant.KEY_PASSWORD, password);
		intent.setClass(cordova.getActivity(), SysMessageService.class);
		cordova.getActivity().startService(intent);
		Log.i(TAG,"-------start SysMessageService to conn xmpp server...");
		callbackContext.success("Success!By:CH.C");
		Log.i(TAG,"-------callbackContext.success();");
//		callbackContext.error("");
		
	}
	
	
}
